<template>
  <div class="proxy-aide">
    <h1>环境切换与代理助手</h1>
    <div class="current-env">
      当前环境:
      <span id="current-env-name">{{ currentEnv.envName || "未选择" }}</span>
    </div>
    <div class="env-list">
      <div
        v-for="(env, index) in environments"
        :key="index"
        class="env-item"
        :class="{ active: currentEnvIndex === index }"
      >
        <div class="env-name">
          <div>名称：{{ env.envName }}</div>
          <div class="env-item-actions">
            <el-button
              type="success"
              icon="el-icon-check"
              circle
              @click="switchEnv(index)"
            ></el-button>
            <el-button
              type="primary"
              icon="el-icon-edit"
              circle
              @click="editEnv(index)"
            >
            </el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              @click="removeEnv(index)"
            ></el-button>
          </div>
        </div>
        <el-divider></el-divider>
        <ul>
          <li>baseUrl：{{ env.baseUrl }}</li>
          <li>SSOLogoutUrl：{{ env.SSOLogoutUrl }}</li>
          <li>SSOUrl：{{ env.SSOUrl }}</li>
          <li>utilsUrl：{{ env.utilsUrl }}</li>
          <li>websocket：{{ env.websocket }}</li>
        </ul>
      </div>

      <template v-if="operationType">
        <el-input
          size="small"
          v-model="newEnvName"
          placeholder="环境名称：（如：本地开发）"
        ></el-input>
        <el-input
          v-model="baseUrl"
          placeholder="baseUrl：（如：http://localhost:8080）"
          size="small"
        ></el-input>
        <el-input
          v-model="websocket"
          placeholder="websocket:（如：http://localhost:8080）"
          size="small"
        ></el-input>
        <template v-if="operationType == 'edit'">
          <el-input
            v-model="SSOLogoutUrl"
            placeholder="SSOLogoutUrl：（如：http://localhost:8080）"
            size="small"
          ></el-input>
          <el-input
            v-model="SSOUrl"
            placeholder="SSOUrl:（如：http://localhost:8080）"
            size="small"
          ></el-input>
          <el-input
            v-model="utilsUrl"
            placeholder="utilsUrl:（如：http://localhost:8080）"
            size="small"
          ></el-input>
        </template>
      </template>

      <el-button
        class="add-btn"
        size="small"
        type="success"
        color="#4CAF50"
        @click="addEnv"
        >{{ operationType ? "保存环境" : "添加环境" }}</el-button
      >
    </div>
  </div>
</template>

<script>
export default {
  name: "",
  components: {},
  data() {
    return {
      currentEnv: {},
      operationType: "", //add,edit
      currentEnvIndex: "",
      newEnvName: "",
      baseUrl: "", //gms接口地址

      //SSO单点地址
      SSOLogoutUrl: "",
      //SSO退出地址
      SSOUrl: "",
      //websocket地址
      websocket: "",
      //工具地址
      utilsUrl: "",

      environments: [
        // {
        //   envName: "开发环境",
        //   //gms接口地址
        //   baseUrl: "https://console-gms-api-dev.ntplat.com/",
        //   //websocket地址
        //   websocket: "wss://console-cms-api-dev.ntplat.com",
        //   //工具地址
        //   utilsUrl: "https://utils-qa.newtypegames.com",
        //   //SSO单点地址
        //   SSOLogoutUrl: "https://sso-api-dev.taiyouxi.cn/server/oauth",
        //   //SSO退出地址
        //   SSOUrl: "https://sso-dev.taiyouxi.cn/login",
        //   //SSO配置id
        //   ClientId: "gms",
        // },
      ],
    };
  },
  mounted() {
    this.loadEnvs();
  },
  watch: {
    baseUrl(val) {
      if (this.operationType != "edit") {
        this.initData(true);
        if (val) {
          let env = "";
          if (val.includes("-dev.")) {
            env = "-dev";
          } else if (val.includes("-qa.")) {
            env = "-qa";
          }
          this.utilsUrl = `https://utils${env}.newtypegames.com`;
          this.SSOLogoutUrl = `https://sso-api${env}.taiyouxi.cn/server/oauth`;
          this.SSOUrl = `https://sso${env}.taiyouxi.cn/login`;
        }
      }
    },
  },
  methods: {
    // 加载保存的环境配置
    loadEnvs() {
      chrome.storage.local.get(["envs", "currentEnv"], (result) => {
        console.log(result, "--11-");

        const envs = result.envs || [];
        const currentEnv = result.currentEnv;
        if (currentEnv) {
          this.currentEnv = currentEnv;
        }
        // this.currentEnv = currentEnv;
        this.environments = envs;
      });
    },
    // 初始化数据
    initData(status) {
      if (!status) {
        this.baseUrl = "";
        this.newEnvName = "";
        this.websocket = "";
      }

      this.utilsUrl = ``;
      this.SSOLogoutUrl = ``;
      this.SSOUrl = ``;
    },
    addEnv() {
      console.log(666);
      if (this.operationType) {
        if (!this.newEnvName || !this.baseUrl) {
          alert("请输入环境名称和baseUrl");
          return;
        }
        chrome.storage.local.get("envs", (result) => {
          let params = {
            envName: this.newEnvName,
            baseUrl: this.baseUrl, //gms接口地址

            //SSO单点地址
            SSOLogoutUrl: this.SSOLogoutUrl,
            //SSO退出地址
            SSOUrl: this.SSOUrl,
            //websocket地址
            websocket: this.websocket,
            //工具地址
            utilsUrl: this.utilsUrl,
          };
          if (this.operationType == "edit") {
            this.environments.splice(this.currentEnvIndex, 1, params);
          } else {
            this.environments.push(params);
          }
          console.log(
            this.environments,
            "----this.environments",
            this.operationType
          );

          const envs = this.environments;

          chrome.storage.local.set({ envs }, () => {
            console.log("st--success");

            // 清空输入框
            this.initData();
            this.loadEnvs(); // 重新加载列表
            this.operationType = "";
          });
        });
      } else {
        this.operationType = "add";
      }
    },
    editEnv(index) {
      this.currentEnvIndex = index;
      this.operationType = "edit";
      this.newEnvName = this.environments[index].envName;
      this.baseUrl = this.environments[index].baseUrl;
      this.SSOLogoutUrl = this.environments[index].SSOLogoutUrl;
      this.SSOUrl = this.environments[index].SSOUrl;
      this.websocket = this.environments[index].websocket;
      this.utilsUrl = this.environments[index].utilsUrl;
    },
    switchEnv(index) {
      this.currentEnv = index;
      let env = this.environments[index];
      // 保存当前环境
      chrome.storage.local.set({ currentEnv: env }, () => {
        // 保存当前环境到本地存储（供下次页面加载时提前注入）

        // 通知background更新规则和注入脚本
        chrome.runtime.sendMessage(
          {
            action: "switchEnv",
            env: env,
          },
          (response) => {
            if (response.success) {
              this.loadEnvs(); // 重新加载列表显示当前环境
              alert(`已切换至【${env.envName}】`);
              // 强制刷新页面，让提前注入的脚本生效
              chrome.tabs.query(
                { active: true, currentWindow: true },
                (tabs) => {
                  chrome.tabs.reload(tabs[0].id);
                }
              );
            } else {
              alert("切换失败，请重试");
            }
          }
        );
      });
    },
    removeEnv(index) {
      if (this.environments.length <= 1) {
        alert("至少保留一个环境");
        return;
      }
      this.environments.splice(index, 1);

      chrome.storage.local.set({ envs: this.environments }, this.loadEnvs);

      // 如果删除的是当前环境，清除当前环境
      if (
        this.environments.findIndex(
          (env) => env.baseUrl === this.currentEnv.baseUrl
        ) === -1
      ) {
        this.currentEnv = {};
        chrome.storage.local.set({ currentEnv: null });
      }
    },
  },
};
</script>
<style>
body {
  margin: 0;
}
</style>
<style lang="scss" scoped>
.proxy-aide {
  width: 300px;
  padding: 15px;
  font-family: Arial, sans-serif;
  display: flex;
  align-items: center;
  flex-direction: column;
  justify-content: center;
  border: 1px solid #ddd;
  background-color: #121212;
  color: white;
  h1 {
    // font-size: 14px;
    font-size: 18px;
    font-weight: 700;
  }
  .current-env {
    min-width: 250px;
    padding: 5px;
    background: #f0f7ff;
    border-left: 3px solid #4285f4;
    margin-bottom: 15px;

    font-size: 14px;
    color: #333;
  }
  .el-input {
    margin-top: 4px;
  }

  ul,
  li {
    list-style: none;
    margin: 0;
    padding: 0;

    font-size: 12px;
  }
  .env-list {
    .env-item {
      //   background-color: #29e5bc;
      margin-bottom: 4px;
      padding: 4px;

      ::-webkit-scrollbar {
        width: 4px;
      }
      .env-name {
        // color: #000;
        width: 100%;
        align-items: center;
        margin-bottom: 8px;
        justify-content: space-between;
        display: flex;
        padding: 0 12px;
        font-size: 14px;
        box-sizing: border-box;
        .el-button {
          height: 20px;
          padding: 0 4px;
          line-height: 20px;
          font-size: 12px;
        }
      }
      .el-divider {
        margin: 0 12px;
        width: auto;
      }
      ul {
        // margin: 12px;
        // color: #666;
        box-sizing: border-box;
        overflow-y: auto;
        height: 30px;
        width: 270px;
        li {
          white-space: nowrap;
          word-break: break-all;
          overflow: hidden;
          text-overflow: ellipsis;
          padding: 0 12px;
          box-sizing: border-box;
        }
      }
    }
  }

  .el-button--success {
    background-color: #4caf50;
  }
  .el-button--danger {
    background-color: #f44336;
  }
  .add-btn {
    width: 100%;
    margin-top: 6px;
    background-color: #00bcd4;
  }
}
</style>
